package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    //收货地址查询
    @Override
    public List<Address> findList() {
        //select * from address_book where user_id = ?
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());//通过传入用户id查找线程中用户、
        qw.orderByDesc(Address::getIsDefault);//降序（1>0）将默认地址排在前面
        return addressMapper.selectList(qw);//遍历用户下数据并返回
    }

    //新增收货地址
    @Override
    public void add(Address address) {
        address.setUserId(UserHolder.get().getId());//将接受参数传入线程
        address.setIsDefault(0);//传入为非默认地址
        addressMapper.insert(address);//调用mapper层方法添加
    }

    //设置默认收货地址
    @Override
    public void setDefault(Long id) {
        Address address = new Address();
        address.setIsDefault(0);//将默认地址修改为0传入线程
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());//通过传入用户id查找线程中的用户
        addressMapper.update(address,qw);//调用mapper修改查询到用户id下的默认地址并修改为0

        Address addressSet = new Address();
        addressSet.setIsDefault(1);//将默认地址数值修改为1传入线程
        addressSet.setId(id);//将传入的id存入达到查询
        addressMapper.updateById(addressSet);//将数值封装数据库

    }

    //查看默认收货地址
    @Override
    public Address findDefault() {
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());//通过传入用户id查找线程中用户
        qw.eq(Address::getIsDefault,1);//查询用户中Default为1的数据
        return  addressMapper.selectOne(qw);//调用mapper方法查询并返回单条数据
    }

    //修改收获地址回显
    @Override
    public Address findById(Long id) {
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());//通过传入id查询线程内用户id
        qw.eq(Address::getId,id);
        return addressMapper.selectOne(qw);//遍历用户
    }

    //修改收货地址
    @Override
    public void updateAddress(Address address) {
        addressMapper.updateById(address);
    }

    //删除收货地址
    @Override
    public void delete(Long ids) {
        addressMapper.deleteById(ids);//调用mapper方法删除
    }
}
